package com.ruijiang.service.TaskService.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.ruijiang.constant.StatusConstant;
import com.ruijiang.dto.count.VMTaskCountDto;
import com.ruijiang.dto.count.UserWorkCountDto;
import com.ruijiang.dto.insert.TaskInsertDto;
import com.ruijiang.dto.page.PageTaskDto;
import com.ruijiang.entity.Task;
import com.ruijiang.entity.TaskDetails;
import com.ruijiang.mapper.TaskServiceMapper.TaskMapper;
import com.ruijiang.result.PageResult;
import com.ruijiang.service.TaskService.TaskDetailsService;
import com.ruijiang.service.TaskService.TaskService;
import com.ruijiang.service.UserService.UserService;
import com.ruijiang.vo.task.*;
import com.ruijiang.vo.user.UserGetByIdVO;
import com.ruijiang.vo.user.UserTaskCountVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class TaskServiceImpl extends ServiceImpl<TaskMapper,Task> implements TaskService {


    @Autowired
    TaskMapper taskMapper;

    @Autowired
    TaskDetailsService taskDetailsService;

    @Autowired
    UserService userService;

    private static String STATUS_FLAG = "status";

    private static String COUNT_FLAG = "count";

    /**
     * 工单分页查询
     * @param dto
     * @return
     */
    @Override
    public PageResult getPageList(PageTaskDto dto) {

        PageHelper.startPage(dto.getPageIndex(),dto.getPageSize());
        Page page = (Page) taskMapper.getPageList(dto);
        return PageResult.pageBuild(page);

    }

    @Transactional
    @Override
    public Boolean saveTask(TaskInsertDto dto) {
        Task task = new Task();
        BeanUtils.copyProperties(dto,task);
        task.setTaskCode(getTaskCode());
        task.setTaskStatus(StatusConstant.TASK_PENDING);
        task.setProductTypeId(dto.getProductType());
        task.setCreateTime(LocalDateTime.now());
        UserGetByIdVO user = userService.getById(dto.getAssignorId());
        task.setUserName(user.getUserName());
        super.save(task);

        if (dto.getDetails()!=null){
            List<TaskDetails> details = dto.getDetails();
            taskDetailsService.saveBatch(details);
        }
        return true;
    }

    @Override
    public TaskInfoVO getTaskInfoById(String taskId) {
        TaskInfoVO vo = new TaskInfoVO();

        Task task = getById(taskId);
        BeanUtils.copyProperties(task,vo);
        vo.setProductType(task.getProductTypeId());
        vo.setTaskName(task.getTaskCode());
        vo.setAssignorId(task.getUserId());
        LambdaQueryWrapper<TaskDetails> wrapper = Wrappers.<TaskDetails>lambdaQuery()
                .eq(TaskDetails::getTaskId, taskId);
        TaskDetails taskDetails = taskDetailsService.getOne(wrapper);
        List<TaskDetails> list = new ArrayList<>();
        list.add(taskDetails);
        vo.setDetails(list);
        return vo;
    }


    @Override
    public void cancelTask(String taskId, Task task) {
        String desc = task.getDesc();
        LambdaUpdateWrapper<Task> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(Task::getTaskId,taskId)
               .set(Task::getDesc,desc)
               .set(Task::getTaskStatus,StatusConstant.TASK_CANCELLED);
        update(wrapper);
    }

    /**
     * 获取工单分类信息
     * @param start
     * @param end
     * @return
     */
    @Override
    public List<TaskReportInfoVO> getTaskReportInfo(String start, String end) {
        TaskReportInfoVO vo = new TaskReportInfoVO();
        List<Map<String,String>> countMap = taskMapper.getTaskReportInfo(start, end);
        //按工单分类映射到结果类
        for (Map map:countMap){
            if (map.get(STATUS_FLAG).equals(StatusConstant.TASK_CANCELLED)){  // 更直接的字符串比较

                Object countObj = map.get(COUNT_FLAG);
                if (countObj != null) {
                    vo.setCancelTotal(((Long) countObj).intValue());
                }
            }else if (map.get(STATUS_FLAG).equals(StatusConstant.TASK_PROCESSING)){

                Object countObj = map.get(COUNT_FLAG);
                if (countObj != null) {
                    vo.setProgressTotal(((Long) countObj).intValue());
                }
            }else if (map.get(STATUS_FLAG).equals(StatusConstant.TASK_COMPLETED)){

                Object countObj = map.get(COUNT_FLAG);
                if (countObj != null) {
                    vo.setCompletedTotal(((Long) countObj).intValue());
                }
            }else {
                continue;
            }
        }
        //获取工单总数
        vo.setTotal(taskMapper.getTotalCount());
        //获取员工数量
        vo.setWorkerCount(taskMapper.getUserTotal());
        List<TaskReportInfoVO> list =new ArrayList<>();
        list.add(vo);
        return list;
    }

    /**
     * 工单状态统计
     * @param start
     * @param end
     * @return
     */
    @Override
    public List<CollectReportVO> CollectReport(String start, String end) {

        CollectReportVO vo = new CollectReportVO();
        List<Map<String,String>> countMap = taskMapper.getTaskReportInfo(start, end);

        for (Map map:countMap){
            if (map.get(STATUS_FLAG).equals(StatusConstant.TASK_CANCELLED)){  // 更直接的字符串比较

                Object countObj = map.get(COUNT_FLAG);
                if (countObj != null) {
                    vo.setCancelCount(((Long) countObj).intValue());
                }
            }else if (map.get(STATUS_FLAG).equals(StatusConstant.TASK_PROCESSING)){

                Object countObj = map.get(COUNT_FLAG);
                if (countObj != null) {
                    vo.setProgressCount(((Long) countObj).intValue());
                }
            }else if (map.get(STATUS_FLAG).equals(StatusConstant.TASK_COMPLETED)){

                Object countObj = map.get(COUNT_FLAG);
                if (countObj != null) {
                    vo.setFinishCount(((Long) countObj).intValue());
                }
            }else {
                continue;
            }
        }

        ArrayList<CollectReportVO> voList = new ArrayList<>();
        voList.add(vo);
        return voList;
    }

    @Override
    public List<UserWorkCountVO> getUserWorkTop10(String start, String end, Boolean isRepair, String regionId) {

        List<UserWorkCountVO> vo= taskMapper.getUserWorkTop10(start, end,isRepair,regionId);
        return vo;
    }

    @Override
    public UserTaskCountVO getUserWork(UserWorkCountDto dto) {
        return taskMapper.getUserWork(dto);
    }

    @Override
    public Integer getVMSupplyCount(String innerCode, String start, String end, VMTaskCountDto dto) {
        Integer vmSupplyCount = taskMapper.getVMTaskCount(innerCode, start, end, dto,4,2);
        log.info(vmSupplyCount.toString());
        return vmSupplyCount;
    }

    @Override
    public Integer getVMRepairCount(String innerCode, String start, String end, VMTaskCountDto dto) {
        Integer repairCount = taskMapper.getVMTaskCount(innerCode, start, end, dto,4,3);
        log.info(repairCount.toString());
        return repairCount;
    }

    /**
     * 获取taskCode
     * @return
     */
    String getTaskCode(){
        String taskCodePre = LocalDateTime.now().format(
                DateTimeFormatter.ofPattern("yyyyMMdd")
        ).toString();
        return taskCodePre+taskMapper.getTaskCode(taskCodePre);
    }
}
